<?php

namespace Frieza\Modules\Article\Controllers;

use App\Admin\Controllers\WorkBaseController;
use App\Admin\Extensions\WorkContent as Content;
use Doraemon\cache\Article;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Doraemon\model\Article as dbArticle;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\tools\ImgUrl;
use Doraemon\cache\Queue;
use Illuminate\Support\MessageBag;

class ArticleController extends WorkBaseController
{

    const NOT_IN_HAPPY_ACTIVITY_SCORE  = 65;

    const FINE_SCORE = 70; // 优秀

    const ORDINARY_SCORE = 60; //普通

    const NOT_FINE_SCORE = 5;//差

    const FINE_MSGCODE = 230;

    const ORDINARY_MSGCODE = 228;

    const NOT_FINE_MSGCODE = 227;

    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    public function index(Request $request, Content $content)
    {
        $requestParams = $request->all();
        $condition = [];
        if (isset($requestParams['aid']) && $requestParams['aid']) {
            $condition['aid'] =$requestParams['aid'];
        } else {

            if (isset($requestParams['publish_time'])) {
                if (isset($requestParams['publish_time']['start']) && strlen($requestParams['publish_time']['start']) > 0) {
                    $condition['publish_time[>=]'] = strtotime($requestParams['publish_time']['start']);
                }
                if (isset($requestParams['publish_time']['end']) && strlen($requestParams['publish_time']['end']) > 0) {
                    $condition['publish_time[<=]'] = strtotime($requestParams['publish_time']['end']);
                }
            }

        }
        $total = dbArticle::getCountByWhere($condition);

        $pageSize = $request->input("per_page", 10);
        $page = $request->input("page", 1);
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $condition['ORDER'] = ['publish_time' => 'DESC'];

        $list = dbArticle::getAritcleByWhere($condition);

        if($list && is_array($list))
        {
             foreach($list as &$val){
                 $val['cover_img_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $val['cover_pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
             }
        }
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('aid', '文章id');
                        $filter->between('push_time', '发布时间')->datetime();
                    });
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();

                $grid->column("aid", '文章id');
                $grid->column("title", '文章标题');
                $grid->column("cover_img_url", '文章封面')->image();
                $grid->column('publish_time', '发布时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->publish_time);
                });
                $grid->column('admin_score', '文章质量')->width(300)->display(function() {
                        return $this->admin_score;

                });

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->append('<a href="/admin/article/edit/' . $actions->row->aid . '" class="fa fa-edit">编辑</a>');

                });

            });
        $tab = new Tab();
        $tab->add('整屋列表', $gridList->render());

        $content->row($tab);
        return $content
            ->header('整屋列表')
            ->breadcrumb(['text' => '整屋列表']);
    }


    //添加或者修改预算表
    public function edit(Request $request,Content $content ,$aid = 0)
    {
        $request = $request->all();
        $aid = $request['aid'] ? : $aid;
        return $content
          ->row(self::editAction($request, $aid));
    }

    //修改列表
    public  function editAction($request = []  , $aid = 0)
    {
        if($aid == 0){
            $data = [];
        }else{
            $data =  dbArticle::getArticle($aid);
        }
        if($data['cover_pic_id']){
            $data['cover_img_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $data['cover_pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
        }
        if($data['admin_score']){
            if($data['admin_score'] <= 5){
                $data['quality']  = "差";
            }elseif($data['admin_score'] <= 60){
                $data['quality']  = "普通";
            }else{
                $data['quality']  = "优质";
            }
            if($data['admin_id'] >0){
                $data['name'] = Admin::user()->find($data['admin_id'])->name;
            }
        }
        $form = new Form($data);
        if(empty($data)){
            $form->disableReset();
            $form->disableSubmit();
            $form->html('<h1>文章不存在或者被删除！</h1>');
            return $form->render();
        }
        if($aid > 0){
            $form->hidden('aid');
        }
        if($data['admin_id'] >0){
            $form->display("name" , " 审核人");
        }
        $form->display("aid" ,'文章id')->disable();
        $form->display("title" , "标题")->disable();
        $form->html('<img src='.$data['cover_img_url'].' style="width:40%"/>',  '封面');
        if($data['admin_score'] > 0){
            $form->display("quality" , " 质量");
            if($data['adm_remark']){
                $form->display("adm_remark" , "文章备注");
            }
           // $form->disableSubmit();
        }
        if($data['status'] == dbArticle::STATUS_SUCCESS){
            $form->disableSubmit();
        }else{
            $form->radio('score' , "打分") ->options([
                '5' => '差',
                '60' => '普通',
                '70' => "优秀",
                '65' => '普通 + 不进拜年活动列表'
            ])->required();
            $form->action('/admin/article/score');
        }

        $form->disableReset();
        return $form->render();
    }


    //提交修改
    public function score(Request $request)
    {
        $request = $request->all();
        $aid = $request['aid'];
        $score = $request['score'];
        $info = dbArticle::getArticle($aid);

        //更新check_time
        if ($info['check_time'] == 0) {
            dbArticle::updateArticle($aid , ['check_time' => time()]);
            Queue::insertQueue("TotalArticle/updateTotalArticle" , ['article_id' =>$aid]);
        }
        if($score == self::NOT_IN_HAPPY_ACTIVITY_SCORE){
             $remark_str= '';
            if($info['adm_remark']){
                $remark_array  = array_filter(explode("," , $info['adm_remark']));
                $remark_array =  array_diff($remark_array , ['拜年活动不进列表']);
                $remark_str = implode("," , $remark_array);
            }
            $remark_str = trim($remark_str.",拜年活动不进列表" , ",");
            $score  = 60;

            $rs =  dbArticle::updateArticle($aid , [
                 'admin_score' => $score,
                 'adm_remark' => $remark_str,
                 'status' => dbArticle::STATUS_SUCCESS,
                 'admin_id' =>Admin::user()->id,
            ]);

        }else{
            $remark_str= '';
            if($info['adm_remark']){
                $remark_array  = array_filter(explode("," , $info['adm_remark']));
                $remark_array =  array_diff($remark_array , ['拜年活动不进列表']);
                $remark_str = implode("," , $remark_array);
            }
            $rs =   dbArticle::updateArticle($aid , [
                 'admin_score' => $score,
                 'adm_remark' => $remark_str,
                 'status' => dbArticle::STATUS_SUCCESS,
                 'admin_id' => Admin::user()->id,
            ]);
        }
        if($rs){
            Queue::insertQueue("TotalArticle/updateTotalArticle" , ['article_id' =>$aid]);
            Article::delete($aid);
            Queue::insertQueue('Article/updateSolr', ['article_id' =>$aid]);
            if($score > 10){
                //如果打分高于10分，投wiki队列
                \Doraemon\amqp\Queue::insertQueue('queue/wiki/afterAuditContent', array(
                    'obj_id' => $aid,
                ), \Doraemon\amqp\Queue::QUEUE_BIZ);
            }

            $success = new MessageBag([
                'title' => '操作成功'
            ]);

            //发送审核消息

            if($info['admin_score'] != $score){
                $this->sendMsg($info , $score);
            }
            //发送审核消息

            return redirect('/admin/article/edit/'.$aid)->with(compact('success'));
        }else{
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            return redirect('/admin/article/edit/'.$aid)->with(compact('error'));
        }

    }


    /**
     * @deprecated
     * @param $info
     * @param $score
     * @return void
     */
    public function sendMsg($info , $score)
    {
        $msgCode = 0 ;
        $link = '';
        switch($score){
            case self::FINE_SCORE:
                $msgCode = self::FINE_MSGCODE;
                break;
            case self::ORDINARY_SCORE:
                $msgCode = self::ORDINARY_MSGCODE;
                break;
            case self::NOT_FINE_SCORE:
                $msgCode = self::NOT_FINE_MSGCODE;
                $link ="hhz://user_article_new:".$info['uid'];
                break;
            default:
                break;
        }
        if($msgCode){
            $queueData = [
                'msgCode' => $msgCode,
                'to_uid' => $info['uid']
            ];
            if($link){
                $queueData['msgParams'] = [
                    'link' => $link
                ];
            }
            Queue::insertQueue('queue/Sysmsg/Send', $queueData, Queue::QUEUE_DORAEMON);
        }
    }


}